package com.delivery.activity;


import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.delivery.common.DatabaseHelper;
import com.delivery.module.ConfigModule;
import com.delivery.utils.NetUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

/**
 * activity调用js
 * @author Administrator
 *
 */
public class ContactWebView extends Activity {
	private static final String TAG = "MainActivity";
	private WebView webview;

	private SharedPreferences sharedata;
	private String from;

	 private WebView mWebView;   
     private Handler mHandler = new Handler();   
     
     private ImageView imageView;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.contact);
		mWebView = (WebView) findViewById(R.id.getWebView);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);		
		ProxyBridge proxy = new ProxyBridge();
		mWebView.addJavascriptInterface(proxy, "AliansBridge");
		mWebView.loadUrl(ConfigModule.GET_CONTACT_URL);
//		mWebView.loadUrl("file:///android_asset/3G/msg.html");
		mWebView.setWebViewClient(new MyWebViewClient());
		mWebView.setWebChromeClient(new MyWebChromeClient() {
		});
		DatabaseHelper  dbHelper = new DatabaseHelper(ContactWebView.this,"webcall");
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		//mWebView.loadDataWithBaseURL("file:///android_asset/3G/demo.html", "dddddd", "text/html", "UTF-8", null);
		//mWebView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl)
	}
	
	
	private class MyWebViewClient extends WebViewClient {
		@Override
		// 在WebView中显示页面,而不是默认浏览器中显示页面
		// 即不是在新打开的activity中显示页面，而是在原来的activity中显示
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if ("client".equalsIgnoreCase(from)) {// 如果从客户端取数据
				String data = getHtml(url);
				view.loadDataWithBaseURL("file:///android_asset/", data,
						"text/html", "UTF-8", null);
			} else if ("server".equalsIgnoreCase(from)) {// 如果从服务器端取数据
				view.loadUrl(url);
			}
			return true;
		}
	}
	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			AlertDialog.Builder b = new AlertDialog.Builder(ContactWebView.this);
			b.setTitle("Alert");
			b.setMessage(message);
			b.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b.setCancelable(false);
			b.create();
			b.show();
			return true;
		};
	}
	private String getHtml(String urlpath) {
		// String urlpath ="http://221.130.176.145";
		try {
			URL url = new URL(urlpath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			Log.i(TAG, String.valueOf(conn.getResponseCode()));
			// 请求成功
			if (conn.getResponseCode() == 200) {
				// 获取服务器返回的数据
				byte[] bytedata = NetUtils.readStream(conn.getInputStream());
				Log.i(TAG, new String(bytedata, "utf-8"));

				return new String(bytedata, "utf-8");
			}
		} catch (Exception e) {
			Log.i(TAG, e.toString());
			AlertDialog.Builder b = new AlertDialog.Builder(ContactWebView.this);
			b.setTitle("Alert");
			b.setMessage("对不起，连接已超时，请重新连接");
			b.setPositiveButton(android.R.string.ok,
					new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			b.setCancelable(false);
			b.create();
			b.show();
			return "";
		}
		return "";
	}

	class ProxyBridge {
		
		public String getJsonHistory(){
			return "[{\"name\":\"李四\",\"age\":\"12\"},{\"name\":\"张三\",\"age\":\"26\"}]";
		}
		
		/**
		 * 根据Id查询聊天历史记录
		 * @param id
		 * @param pageSize
		 * @param currentPage
		 * @return
		 */
		public String getChatMsgHitory(String id,String pageSize,String currentPage){
			SQLiteDatabase db = null;
			Cursor cursor = null;
			StringBuffer sb = new StringBuffer();
			int page = 2;
			int current = 1;			
			if(!isNotEmptyAndNull(id)){
				return "[{}]";
			}
			if(isNotEmptyAndNull(pageSize)){
				page = Integer.parseInt(pageSize); 
			}
			if(isNotEmptyAndNull(currentPage)){
				current = Integer.parseInt(currentPage);
			}
			//int totalNum = page*current;
			try {	
				DatabaseHelper dbHelper = new DatabaseHelper(ContactWebView.this, "webcall");
				db = dbHelper.getReadableDatabase();
				String sql = "select * from history  where id=? order by msgTime DESC limit ? offset ? ";				
		    	cursor = db.rawQuery(sql, new String[]{id,String.valueOf(page),String.valueOf(current)});
		    	//cursor = db.query("history", new String[]{"msgBody","msgType"}, "id=?", new String[]{""}, "", "", "");
		    	sb.append("[");
		    	while(cursor.moveToNext()){	    		
		    		System.out.println(cursor.getString(cursor.getColumnIndex("msgBody")));
		    		sb.append("{\"msgToName\":\""+cursor.getString(cursor.getColumnIndex("msgToName"))+"\",");
		    		sb.append("\"msgBody\":\""+cursor.getString(cursor.getColumnIndex("msgBody"))+"\",");
		    		sb.append("\"msgType\":\""+cursor.getString(cursor.getColumnIndex("msgType"))+"\",");
		    		sb.append("\"msgTime\":\""+cursor.getString(cursor.getColumnIndex("msgTime"))+"\"},");
		    	}
		    	if(sb.toString().endsWith(",")){
		    		sb.delete(sb.length()-1, sb.length());
		    	}
		    	sb.append("]");
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(null != cursor){
					cursor.close();
					cursor = null;
				}
				if(null != db){
					db.close();
					db = null;
				}
			}
			return sb.toString();
		}
		
		/**
		 * 添加聊天消息
		 * @param id
		 * @param msgToName
		 * @param msgBody
		 * @param msgType
		 * @param msgTime
		 * @return
		 */
		public String addChatMsg(String id, String msgToName, String msgBody,String msgType,String msgTime){
			DatabaseHelper dbHelper = new DatabaseHelper(ContactWebView.this, "webcall");
			ContentValues content = new ContentValues();
			content.put("id", id);
			content.put("msgToName", msgToName);
			content.put("msgType", msgType);
			content.put("msgBody", msgBody);
			content.put("msgTime", msgTime);
			content.put("time", getDate());
			String rowId  = "";
			SQLiteDatabase db = null;
			try {
				db = dbHelper.getWritableDatabase();
				rowId = String.valueOf(db.insert("history",null, content));
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(null != db){
					db.close();
					db = null;
				}
			}
			return rowId;
		}
		
		/**
		 * 删除聊天记录
		 */
		public void delChatHistory(String month){
			DatabaseHelper dbHelper = new DatabaseHelper(ContactWebView.this, "webcall");
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.delete("history", "msgTime < ?", new String[]{getDate(month)});
		}
	}
	
	public String getDate(String month){
		if(!isNotEmptyAndNull(month)){
			month = "3";
		}
		Calendar cal =Calendar.getInstance();
		cal.add(Calendar.MONTH, -Integer.parseInt(month));
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(cal.getTime());
	}
	
	public String getDate(){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(new Date());
	}
	
	public boolean isNotEmptyAndNull(String str){
		return null != str && !"".equals(str) && !"null".equals(str);
	}
	
}
